import { EnginePage, EngineTemplate } from './../../../models';
import { Component, OnInit, Input, ViewChildren, QueryList, ViewContainerRef, AfterViewInit } from '@angular/core';

import { RenderComponentConfig } from '../../../models/render-component-config';
import { TemplateMapTool } from '../../../tools/template-map.tool';
import { BaseContainerComponent } from '../base-container.component';

@Component({
  selector: 'zepride-page-container',
  templateUrl: './page-container.component.html',
  styleUrls: ['./page-container.component.less']
})
export class PageContainerComponent extends BaseContainerComponent implements OnInit, AfterViewInit {

  @ViewChildren('templateViewContainerRef', { read: ViewContainerRef }) templateViewContainerRef: QueryList<ViewContainerRef>;
  private _flowNodePage: EnginePage;

  @Input() set data(flowNodePage: EnginePage) {
    this._flowNodePage = flowNodePage;
  }

  get flowNodePage() {
    return this._flowNodePage;
  }

  ngOnInit(): void { }

  ngAfterViewInit() {
    const temps = this.flowNodePage.templates;
    this.renderTemplates(temps);
  }

  renderTemplates(templates: EngineTemplate[]) {
    const refs = this.templateViewContainerRef.toArray();
    templates.forEach((temp, index) => {
      const config = this.generateRenderConfig(temp, refs[index]);
      if (config) {
        this.engineService.renderComponent(config);
      }
    });
  }

  generateRenderConfig(template: EngineTemplate, viewContainerRef: ViewContainerRef) {
    const renderItem = TemplateMapTool.current.getRenderItem('template', template);
    if (renderItem) {
      const config: RenderComponentConfig = {
        renderItem,
        viewContainerRef
      };
      return config;
    } else {
      return null;
    }
  }
}
